<template>
  <!--公司信息	-->
  <div>
    <FormPanel ref="FormPanel" :list="initForm" :cols="2" :formType="formType" :labelWidth="180" :isSubmitBtn="false" @formChange="formChangeHandle" class="mtop" />
  </div>
</template>

<script>
  import { dictionary } from '@/utils/dictMixin';
  import * as types from '@/api/cms-api/origin/originInfo/types';
  import vm from './bridge';
  import { getRegion, getCommunity, getLevelOneArea, getLevelTwoAndThreeArea, queryAreaManagerByOrgId} from '@/api/cms-common/dealerdata/index';

  export default {
    mixins: [dictionary],
    model: {
      prop: 'pdata',
      event: 'click'
    },
    props: {
      pdata: {
        type: Object,
        default: () => ({})
      },
      formType: {
        type: String,
        required: true
      },
      formOptions: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        initForm: this.initFormFun(),
        ORG_TYPE_MARKETING_WAR_AREA:15061013, //C端战区
        ORG_TYPE_MARKETING_BIG_AREA:15061014, //C端大区
        ORG_TYPE_MARKETING_SMALL_AREA:15061015, //C端小区
        // ORG_TYPE_OUTING_WAR_AREA:15061016, //B端战区
        // ORG_TYPE_OUTING_BIG_AREA:15061017, //B端大区
        // ORG_TYPE_OUTING_SMALL_AREA:15061018, //B端小区
        // ORG_TYPE_SERVICE_BIG_AREA:15061019, //服务大区
        // ORG_TYPE_SERVICE_SMALL_AREA:15061020, //服务小区
        hiddenFormData:{},
      };
    },
    async mounted() {
      await this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA,'marketingWarArea');
      // await this.getTopLevelArea(this.ORG_TYPE_OUTING_WAR_AREA,'outingWarArea');
    },
    methods: {
      //初始化数据
      async init(data) {
        //取出明细信息中的销售区域信息
        let pdataCopy = JSON.parse(JSON.stringify(this.pdata.salesAreaInfo));
        // await this.getBigArea();
        // await this.changeBigArea(pdataCopy.serviceBigArea,false);
        await this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA,'marketingWarArea');
        await this.changeTopAndMiddleLevelArea(pdataCopy.marketingWarArea,this.ORG_TYPE_MARKETING_BIG_AREA
          ,'marketingWarArea','marketingBigArea',false);
        await this.changeTopAndMiddleLevelArea(pdataCopy.marketingBigArea,this.ORG_TYPE_MARKETING_SMALL_AREA
          ,'marketingBigArea','marketingSmallArea',false);
        pdataCopy.marketingWarAreaManager  = await this.getAreaManager(pdataCopy.marketingWarArea);
        pdataCopy.marketingBigAreaManager  = await this.getAreaManager(pdataCopy.marketingBigArea);
        pdataCopy.marketingSmallAreaManager = await this.getAreaManager(pdataCopy.marketingSmallArea);
        // await this.getTopLevelArea(this.ORG_TYPE_OUTING_WAR_AREA,'outingWarArea');
        // this.changeTopAndMiddleLevelArea(pdataCopy.outingWarArea,this.ORG_TYPE_OUTING_BIG_AREA,
        //   'outingWarArea','outingBigArea',false);
        // this.changeTopAndMiddleLevelArea(pdataCopy.outingBigArea,this.ORG_TYPE_OUTING_SMALL_AREA,
        //   'outingBigArea','outingSmallArea',false);
        await this.initForm.forEach(x => {
          if (pdataCopy[x.fieldName]) {
            x.initialValue = pdataCopy[x.fieldName];
          }
        });


      },

      //获取大小区数据
      //初始化数据（带触发事件，为经销商提报添加的）
      initPre(data) {
        // if (this.formType != 'show') {
        //   if (!this.pdata.companyName) {
        //     this.pdata.companyName = this.pdata.dealerName;
        //   }
        //   // vm.$emit('changeDealerType', this.pdata);
        //   vm.$emit('changeDealerType', this.pdata.dealerType);
        //   // this.supplementChangeDealerType(this.pdata.dealerType);
        // }
        this.initForm.forEach(x => {
          if (this.pdata[x.fieldName]) {
            x.initialValue = this.pdata[x.fieldName];
          }
        });
      },
      //表单验证通过后
      formChangeHandle(val) {
        this.pdata = Object.assign(this.pdata, val);
        //传递数据到父组件里
        this.$emit('click', this.pdata);
        //触发外部的事件，以标志着本表单已经准备完毕
        // this.$emit('formchange', this.pdata);
      },
      //开放的提交方法
      async saveDialog() {
        let flag = true;
        let data = this.$refs.FormPanel.SUBMIT_FORM();
        console.log("data:",data);
        await this.$refs.FormPanel.$refs.form.validate().then(res => {
          console.log("res1:", res);
        }).catch(err => {
          console.log("err1:", err);
          flag = false;
        });

        // if(!this.checkRequired(data)){
        //   flag = false;
        //   this.$notify.error("B端或C端战区必填");
        // }
        console.log("flag:", flag);
        return flag;
        // this.$notify.warning({title: '提示信息',message:'只能选择一条记录'});
      },

      // checkRequired(data){
      //   let f1 = !this.isEmpty(data.marketingWarArea) && !this.isEmpty(data.marketingBigArea) && !this.isEmpty(data.marketingSmallArea);
      //     // && this.isEmpty(data.outingWarArea) && this.isEmpty(data.outingBigArea) && this.isEmpty(data.outingSmallArea);
      //
      //   let f2 = !this.isEmpty(data.outingWarArea) && !this.isEmpty(data.outingBigArea) && !this.isEmpty(data.outingSmallArea);
      //     // && this.isEmpty(data.marketingWarArea) && this.isEmpty(data.marketingBigArea) && this.isEmpty(data.marketingSmallArea);
      //
      //   if(f1 || f2){
      //     return true;
      //   }else{
      //     return false;
      //   }
      //
      // },
      // isEmpty(obj){
      //   return obj == null || obj == "";
      // },
      //表单数据
      initFormFun() {
        let bt = { required: true, message: '必填', trigger: ['change', 'blur'] };
        let btl = [bt];
        let sj = { pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '请填写正确的手机号', trigger: ['change', 'blur'] };
        let email = { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' };
        let jy = { disabled: true };
        let yc = { hidden: true };
        return [
          {
            type: 'SELECT',
            label: '营销战区',
            fieldName: 'marketingWarArea',
            placeholder: '请选择',
            initialValue: '',
            itemList: [],
            rules: btl,
            change: val => {
              this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_MARKETING_BIG_AREA,
                'marketingWarArea','marketingBigArea');
            },
          },
          // {
          //   type: 'INPUT',
          //   label: 'C端战区名称',
          //   fieldName: 'marketingWarAreaName',
          //   rows: 1,
          //   initialValue: '',
          //   hidden:true
          // },
          {
            type: 'INPUT',
            label: '战区负责人',
            fieldName: 'marketingWarAreaManager',
            rows: 1,
            initialValue: '',
            placeholder: '请输入',
            maxlength: 50,
            disabled:true,
          },
          {
            type: 'SELECT',
            label: '所属大区',
            fieldName: 'marketingBigArea',
            placeholder: '请选择',
            initialValue: '',
            itemList: [],
            rules: btl,
            change: val => {
              this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_MARKETING_SMALL_AREA,
                'marketingBigArea','marketingSmallArea');
            },
          },
          // {
          //   type: 'INPUT',
          //   label: 'C端大区名称',
          //   fieldName: 'marketingBigAreaName',
          //   rows: 1,
          //   initialValue: '',
          //   hidden:true
          // },
          {
            type: 'INPUT',
            label: '大区负责人',
            fieldName: 'marketingBigAreaManager',
            rows: 1,
            initialValue: '',
            placeholder: '请输入',
            maxlength: 50,
            disabled:true,
          },
          {
            type: 'SELECT',
            label: '所属区域',
            rules: btl,
            fieldName: 'marketingSmallArea',
            placeholder: '请选择',
            initialValue: '',
            itemList: [],
            change: val => {
              this.changeBottomLevelArea(val, 'marketingSmallArea');
            },
          },
          // {
          //   type: 'INPUT',
          //   label: 'C端小区名称',
          //   fieldName: 'marketingSmallAreaName',
          //   rows: 1,
          //   initialValue: '',
          //   hidden:true
          // },
          {
            type: 'INPUT',
            label: '区域经理',
            fieldName: 'marketingSmallAreaManager',
            rows: 1,
            itemList: [],
            initialValue: '',
            placeholder: '请输入',
            maxlength: 50,
            disabled:true,
          },

          // {
          //   type: 'SELECT',
          //   label: 'B端战区',
          //   fieldName: 'outingWarArea',
          //   placeholder: '请选择',
          //   initialValue: '',
          //   itemList: [],
          //   change: val => {
          //     this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_OUTING_BIG_AREA,
          //       'outingWarArea','outingBigArea');
          //   },
          // },
          // {
          //   type: 'INPUT',
          //   label: 'B端战区名称',
          //   fieldName: 'outingWarAreaName',
          //   rows: 1,
          //   initialValue: '',
          //   hidden:true
          // },
          // {
          //   type: 'INPUT',
          //   label: 'B端战区负责人',
          //   fieldName: 'outingWarAreaManager',
          //   rows: 1,
          //   initialValue: '',
          //   placeholder: '请输入',
          //   maxlength: 50,
          // },
          // {
          //   type: 'SELECT',
          //   label: 'B端大区',
          //   fieldName: 'outingBigArea',
          //   placeholder: '请选择',
          //   initialValue: '',
          //   itemList: [],
          //   change: val => {
          //     this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_OUTING_SMALL_AREA,
          //       'outingBigArea','outingSmallArea');
          //   },
          // },
          // {
          //   type: 'INPUT',
          //   label: 'B端大区名称',
          //   fieldName: 'outingBigAreaName',
          //   rows: 1,
          //   initialValue: '',
          //   hidden:true
          // },
          // {
          //   type: 'INPUT',
          //   label: 'B端大区负责人',
          //   fieldName: 'outingBigAreaManager',
          //   rows: 1,
          //   initialValue: '',
          //   placeholder: '请输入',
          //   maxlength: 50,
          // },
          // {
          //   type: 'SELECT',
          //   label: 'B端小区',
          //   fieldName: 'outingSmallArea',
          //   placeholder: '请选择',
          //   initialValue: '',
          //   itemList: [],
          //   change: val => {
          //     this.changeBottomLevelArea(val, 'outingSmallArea');
          //   },
          // },
          // {
          //   type: 'INPUT',
          //   label: 'B端小区名称',
          //   fieldName: 'outingSmallAreaName',
          //   rows: 1,
          //   initialValue: '',
          //   hidden:true
          // },
          // {
          //   type: 'INPUT',
          //   label: 'B端小区负责人',
          //   fieldName: 'outingSmallAreaManager',
          //   rows: 1,
          //   initialValue: '',
          //   placeholder: '请输入',
          //   maxlength: 50,
          // },
        ];
          },

      //获取区域经理
      async getAreaManager(orgId){
        if(orgId == null || orgId == "" || orgId == undefined){
          return "";
        }
        let res = await queryAreaManagerByOrgId(orgId);
        let list = res.data;
        if(!Array.isArray(list) || list == null || list.length == 0){
          return "";
        }

        let nameArray = new Array();
        list.forEach(t => {
          nameArray.push(t.employeeName);
        })
        return nameArray.join(",");
      },

      //获取顶层组织数据
      async getTopLevelArea(areaType, filedName) {
        const res = await getLevelOneArea(areaType);
        if (res.resultCode === 200) {
          this.initForm.find(item => item.fieldName === filedName).itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
        }
      },

      //顶层和中层组织数据修改
      async changeTopAndMiddleLevelArea(deptId, sonAreaType, parentFieldName, sonFieldName, flag = true) {
        let formData = this.hiddenFormData;
        let parentArea = this.initForm.find(item => item.fieldName === parentFieldName);
        let sonArea = this.initForm.find(item => item.fieldName === sonFieldName);
        if (!deptId) {
          formData[`${parentFieldName}Name`] = '';
          sonArea.initialValue = '';
          sonArea.itemList = [];
        } else {
          if(parentArea.itemList.length != 0){
            formData[`${parentFieldName}Name`] = parentArea.itemList.find(item => item.value === deptId).text;
          }
          if (flag) {
            //正常的级联，清空原来选择的数据
            sonArea.initialValue = '';
          }
          const res = await getLevelTwoAndThreeArea(sonAreaType, deptId);
          if (res.resultCode === 200) {
            sonArea.itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
          }
        }
        //区域经理
        let manager = this.initForm.find(item => item.fieldName === `${parentFieldName}Manager`);
        if(manager){
          manager.initialValue = await this.getAreaManager(deptId);
        }
      },

      //底层数据修改
      async changeBottomLevelArea(deptId, fieldName){
        let formData = this.hiddenFormData;
        let area = this.initForm.find(item => item.fieldName === fieldName);
        if (!deptId) {
          formData[`${fieldName}Name`] = '';
        }else{
          if(area.itemList.length != 0){
            formData[`${fieldName}Name`] = area.itemList.find(item => item.value === deptId).text;
          }
        }
        //区域经理
        let manager = this.initForm.find(item => item.fieldName === `${fieldName}Manager`);
        if(manager){
          manager.initialValue = await this.getAreaManager(deptId);
        }
      },


    }
  };
</script>
